package com.milepost.workflow.flowinst.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.milepost.workflow.flowinst.entity.FlowInstSeqEntity;
import com.milepost.workflow.flowinst.mapper.FlowInstSeqMapper;
import com.milepost.workflow.flowinst.service.FlowInstSeqService;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author huarf
 * @Description
 * @create 2022-03-31 23:53
 */
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
@EnableScheduling
public class FlowInstSeqServiceImpl extends ServiceImpl<FlowInstSeqMapper, FlowInstSeqEntity> implements FlowInstSeqService {

    private final FlowInstSeqMapper flowInstSeqMapper;

    /**
     * 定时任务，每天0点清空表数据，自增从0开始
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void truncate() {

        flowInstSeqMapper.truncate();
    }

    @Override
    public FlowInstSeqEntity nextSeq() {

        FlowInstSeqEntity flowInstSeqEntity = new FlowInstSeqEntity(new Date());
        baseMapper.insert(flowInstSeqEntity);
        return flowInstSeqEntity;
    }

    /**
     * 依赖于mysql自增，不需要同步，两个会话在不提交的情况下产生的自增id是不同的，不会冲突
     *
     * @return
     */
    @Override
    public String nextFlowInstSn() {

        FlowInstSeqEntity flowInstSeqEntity = nextSeq();
        long div = flowInstSeqEntity.getId() / 100;
        long mod = flowInstSeqEntity.getId() % 100;
        char c = (char) ('A' + div);
        return DateFormatUtils.format(flowInstSeqEntity.getTs(), "yyyyMMdd") + c + String.format("%02d", mod);
    }

}
